// NBA页面
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../core/nba_service.dart';
import '../core/nba_models.dart';
import 'player_page.dart';
import 'nba_news_detail_page.dart';
import 'package:provider/provider.dart';
import '../core/theme_config.dart';
import 'home_page.dart'; // 导入_PosterCard组件
import '../components/nba_poster_card.dart';

class NbaPage extends StatefulWidget {
  const NbaPage({super.key});

  @override
  State<NbaPage> createState() => _NbaPageState();
}

class _NbaPageState extends State<NbaPage> with TickerProviderStateMixin {
  late TabController _tabController;
  final List<String> _tabTitles = ['直播', '新闻', '集锦', '赛程', '纪录片', '排名'];
  
  // 数据状态
  List<NbaLiveMatch> _liveMatches = [];
  List<NbaNews> _news = [];
  List<NbaHighlight> _highlights = [];
  List<NbaDocumentary> _documentaries = [];
  List<NbaTeam> _teams = [];
  List<NbaSchedule> _schedules = [];
  int _currentSchedulePage = 1;
  bool _loadingMoreSchedules = false;
  bool _hasMoreSchedules = true;
  
  // 新闻分页
  int _currentNewsPage = 1;
  bool _loadingMoreNews = false;
  bool _hasMoreNews = true;
  
  // 集锦分页
  int _currentHighlightsPage = 1;
  bool _loadingMoreHighlights = false;
  bool _hasMoreHighlights = true;
  bool _reachedHighlightsBottom = false;
  
  bool _loading = false;
  // int _currentTabIndex = 0; // 暂时未使用
  
  // 直播日期相关状态
  DateTime _currentLiveDate = DateTime.now();
  bool _loadingLiveMatches = false;
  
  // 赛事类型相关状态
  SportType _currentSportType = SportType.all;
  late TabController _sportTypeTabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: _tabTitles.length,
      vsync: this,
    );
    _tabController.addListener(_handleTabSelection);
    
    // 初始化赛事类型标签控制器
    _sportTypeTabController = TabController(
      initialIndex: SportType.values.indexOf(_currentSportType),
      length: SportType.values.length,
      vsync: this,
    );
    _sportTypeTabController.addListener(_handleSportTypeTabSelection);
    
    _loadData();
  }

  @override
  void dispose() {
    _tabController.dispose();
    _sportTypeTabController.dispose();
    super.dispose();
  }

  void _handleTabSelection() {
    setState(() {});
  }
  
  // 处理赛事类型标签选择
  void _handleSportTypeTabSelection() {
    if (_sportTypeTabController.indexIsChanging) {
      setState(() {
        _currentSportType = SportType.values[_sportTypeTabController.index];
      });
      _loadLiveMatchesWithFilter();
    }
  }
  
  // 加载带筛选条件的直播比赛数据
  Future<void> _loadLiveMatchesWithFilter() async {
    setState(() => _loadingLiveMatches = true);
    try {
      final matches = await NbaService.fetchLiveMatches(
        date: _currentLiveDate,
        sportType: _currentSportType,
      );
      setState(() => _liveMatches = matches);
    } catch (e) {
      print('加载筛选后的直播比赛失败: $e');
    } finally {
      setState(() => _loadingLiveMatches = false);
    }
  }
  
  /// 处理NBA页面特定的按键事件
  void _handleNbaKeyEvent(RawKeyEvent event) {
    if (event is RawKeyDownEvent) {
      final key = event.logicalKey;
      
      // 数字键快捷导航到对应标签页
      if (key == LogicalKeyboardKey.digit1) {
        _tabController.animateTo(0); // 直播
      } else if (key == LogicalKeyboardKey.digit2) {
        _tabController.animateTo(1); // 新闻
      } else if (key == LogicalKeyboardKey.digit3) {
        _tabController.animateTo(2); // 集锦
      } else if (key == LogicalKeyboardKey.digit4) {
        _tabController.animateTo(3); // 赛程
      } else if (key == LogicalKeyboardKey.digit5) {
        _tabController.animateTo(4); // 纪录片
      } else if (key == LogicalKeyboardKey.digit6) {
        _tabController.animateTo(5); // 排名
      }
      
      // 左右方向键切换标签页
      else if (key == LogicalKeyboardKey.arrowRight) {
        final nextIndex = (_tabController.index + 1) % _tabController.length;
        _tabController.animateTo(nextIndex);
      } else if (key == LogicalKeyboardKey.arrowLeft) {
        final prevIndex = (_tabController.index - 1) % _tabController.length;
        _tabController.animateTo(prevIndex < 0 ? _tabController.length - 1 : prevIndex);
      }
      
      // 返回键处理
      else if (key == LogicalKeyboardKey.escape ||
               key == LogicalKeyboardKey.goBack) {
        // 返回上一页
        Navigator.of(context).pop();
        debugPrint('返回按键 - 返回上一页');
      }
    }
  }

  Future<void> _loadData() async {
    setState(() => _loading = true);
    try {
      // 并行加载所有数据
      final results = await Future.wait([
        NbaService.fetchLiveMatches(date: _currentLiveDate, sportType: _currentSportType),
        NbaService.fetchNews(page: 1),
        NbaService.fetchHighlights(page: 1),
        NbaService.fetchSchedules(),
        NbaService.fetchDocumentaries(),
        NbaService.fetchTeamStandings(),
      ]);

      setState(() {
        _liveMatches = results[0] as List<NbaLiveMatch>;
        _news = results[1] as List<NbaNews>;
        _highlights = results[2] as List<NbaHighlight>;
        _schedules = results[3] as List<NbaSchedule>;
        _documentaries = results[4] as List<NbaDocumentary>;
        _teams = results[5] as List<NbaTeam>;
        
        // 重置分页状态
        _currentSchedulePage = 1;
        _hasMoreSchedules = _schedules.length >= 20;
        
        _currentNewsPage = 1;
        _hasMoreNews = _news.length >= 20;
        
        _currentHighlightsPage = 1;
        _hasMoreHighlights = _highlights.length >= 20;
        
        _loading = false;
      });
    } catch (e) {
      print('加载NBA数据失败: $e');
      setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final themeConfig = Provider.of<ThemeConfig>(context);
    
    return RawKeyboardListener(
      focusNode: FocusNode(),
      autofocus: true,
      onKey: (event) {
        _handleNbaKeyEvent(event);
      },
      child: Column(
        children: [
        Expanded(
          child: _loading
              ? const Center(child: CircularProgressIndicator())
              : TabBarView(
                  controller: _tabController,
                  children: [
                    _buildLiveTab(),
                    _buildNewsTab(),
                    _buildHighlightsTab(),
                    _buildSchedulesTab(),
                    _buildDocumentariesTab(),
                    _buildStandingsTab(),
                  ],
                ),
        ),
        _buildBottomNavigationBar(themeConfig),
      ],
      )
    );
  }

  // 构建底部导航栏
  Widget _buildBottomNavigationBar(ThemeConfig themeConfig) {
    final isNarrow = MediaQuery.of(context).size.width < 700;

    final items = _tabTitles.asMap().entries.map((entry) {
      final index = entry.key;
      final title = entry.value;
      final isSelected = _tabController.index == index;

      return GestureDetector(
        onTap: () {
          _tabController.animateTo(index);
          setState(() {});
        },
        child: Container(
          margin: const EdgeInsets.only(right: 12),
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          decoration: BoxDecoration(
            color: isSelected
                ? themeConfig.currentPrimaryColor.withOpacity(0.95)
                : themeConfig.currentPrimaryColor.withOpacity(0.12),
            borderRadius: BorderRadius.circular(25),
            border: Border.all(
              color: isSelected ? themeConfig.currentPrimaryColor : themeConfig.currentPrimaryColor.withOpacity(0.35),
              width: isSelected ? 1.5 : 1,
            ),
            boxShadow: isSelected
                ? [
                    BoxShadow(
                      color: themeConfig.currentPrimaryColor.withOpacity(0.3),
                      blurRadius: 6,
                      offset: const Offset(0, 2),
                    )
                  ]
                : null,
          ),
          child: Text(
            title,
            style: TextStyle(
              fontSize: 14,
              fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
              letterSpacing: 0.5,
              color: isSelected ? Colors.white : themeConfig.currentTextColor,
            ),
          ),
        ),
      );
    }).toList();

    return Container(
      decoration: BoxDecoration(
        gradient: themeConfig.currentGradient,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      padding: EdgeInsets.symmetric(vertical: 12, horizontal: isNarrow ? 0 : 16),
      child: isNarrow
          ? SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            physics: const BouncingScrollPhysics(),
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: Row(children: items),
            )
          : Center(
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: items,
              ),
            ),
    );
  }

  // 直播标签页
  Widget _buildLiveTab() {
    return Column(
      children: [
        _buildSportTypeNavigation(),
        _buildLiveDateNavigation(),
        Expanded(
          child: RefreshIndicator(
            onRefresh: () async {
              final matches = await NbaService.fetchLiveMatches(
                date: _currentLiveDate,
                sportType: _currentSportType,
              );
              setState(() => _liveMatches = matches);
            },
            child: ListView.separated(
              padding: EdgeInsets.zero,
              itemCount: _liveMatches.length,
              separatorBuilder: (context, index) {
                final themeConfig = Provider.of<ThemeConfig>(context);
                return Divider(
                  height: 1,
                  thickness: 0.6,
                  color: themeConfig.currentTextColor.withOpacity(0.08),
                );
              },
              itemBuilder: (context, index) {
                final match = _liveMatches[index];
                return _buildLiveMatchCard(match);
              },
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildLiveMatchCard(NbaLiveMatch match) {
    final themeConfig = Provider.of<ThemeConfig>(context);
    final primary = themeConfig.currentPrimaryColor;
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 比赛信息
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '${match.league}',
                  style: TextStyle(color: themeConfig.currentTextColor.withOpacity(0.6), fontSize: 12),
                ),
                Text(
                  match.matchTime,
                  style: TextStyle(color: themeConfig.currentTextColor.withOpacity(0.6), fontSize: 12),
                ),
              ],
            ),
            const SizedBox(height: 8),
            
            // 球队信息
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                // 主队
                Column(
                  children: [
                    CachedNetworkImage(
                      imageUrl: match.homeLogo,
                      width: 40,
                      height: 40,
                      placeholder: (context, url) => const CircleAvatar(
                        backgroundColor: Colors.grey,
                        child: Icon(Icons.sports_basketball, color: Colors.white),
                      ),
                      errorWidget: (context, url, error) => const CircleAvatar(
                        backgroundColor: Colors.grey,
                        child: Icon(Icons.error, color: Colors.white),
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      match.homeTeam,
                      style: const TextStyle(fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
                
                // 比分
                Column(
                  children: [
                    Text(
                      match.score,
                      style: TextStyle(
                        fontSize: 22,
                        fontWeight: FontWeight.bold,
                        color: primary,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      match.status,
                      style: TextStyle(
                        color: _getStatusColor(match.status),
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
                
                // 客队
                Column(
                  children: [
                    CachedNetworkImage(
                      imageUrl: match.awayLogo,
                      width: 40,
                      height: 40,
                      placeholder: (context, url) => const CircleAvatar(
                        backgroundColor: Colors.grey,
                        child: Icon(Icons.sports_basketball, color: Colors.white),
                      ),
                      errorWidget: (context, url, error) => const CircleAvatar(
                        backgroundColor: Colors.grey,
                        child: Icon(Icons.error, color: Colors.white),
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      match.awayTeam,
                      style: const TextStyle(fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
              ],
            ),
            const SizedBox(height: 6),
            
            // 直播源
            if (match.liveSources.isNotEmpty)
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const SizedBox(height: 8),
                  Wrap(
                    spacing: 4,
                    runSpacing: 4,
                    children: match.liveSources.map((source) {
                      return ActionChip(
                        label: Text('${source.name} (${source.quality})'),
                        onPressed: () => _watchLive(source, match),
                        backgroundColor: primary,
                        labelStyle: const TextStyle(color: Colors.white),
                        labelPadding: const EdgeInsets.symmetric(horizontal: 6),
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      );
                    }).toList(),
                  ),
                ],
              ),
            
            // 集锦链接
            if (match.highlightUrl != null && match.status == '已结束')
              Padding(
                padding: const EdgeInsets.only(top: 8),
                child: OutlinedButton.icon(
                  onPressed: () => _watchHighlight(match.highlightUrl!), 
                  icon: const Icon(Icons.play_arrow),
                  label: const Text('观看集锦'),
                  style: OutlinedButton.styleFrom(
                    foregroundColor: primary,
                    visualDensity: VisualDensity.compact,
                  ),
                ),
              ),
          ],
      ),
    );
  }

  Color _getStatusColor(String status) {
    final themeConfig = Provider.of<ThemeConfig>(context, listen: false);
    final primary = themeConfig.currentPrimaryColor;
    switch (status) {
      case '进行中':
        return primary;
      case '已结束':
        return themeConfig.currentTextColor.withOpacity(0.5);
      default:
        return primary.withOpacity(0.8);
    }
  }

  // 新闻标签页
  Widget _buildNewsTab() {
    if (_news.isEmpty && !_loading) {
      return const Center(child: Text('暂无新闻资讯'));
    }

    return RefreshIndicator(
      onRefresh: () async {
        setState(() {
          _currentNewsPage = 1;
          _hasMoreNews = true;
        });
        final news = await NbaService.fetchNews(page: 1);
        setState(() => _news = news);
      },
      child: ListView.separated(
        padding: EdgeInsets.zero,
        itemCount: _news.length + (_hasMoreNews ? 1 : 0),
        separatorBuilder: (context, index) {
          final themeConfig = Provider.of<ThemeConfig>(context);
          return Divider(
            height: 1,
            thickness: 0.6,
            color: themeConfig.currentTextColor.withOpacity(0.08),
          );
        },
        itemBuilder: (context, index) {
          if (index == _news.length) {
            return _buildLoadMoreNewsButton();
          }
          final news = _news[index];
          return _buildNewsCard(news);
        },
      ),
    );
  }

  // 加载更多新闻按钮
  Widget _buildLoadMoreNewsButton() {
    if (_loadingMoreNews) {
      return const Padding(
        padding: EdgeInsets.all(16.0),
        child: Center(child: CircularProgressIndicator()),
      );
    }
    
    if (!_hasMoreNews) {
      return const Padding(
        padding: EdgeInsets.all(16.0),
        child: Center(child: Text('没有更多新闻了')),
      );
    }
    
    final themeConfig = Provider.of<ThemeConfig>(context);
    final primary = themeConfig.currentPrimaryColor;
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: primary,
          foregroundColor: Colors.white,
        ),
        onPressed: _loadMoreNews,
        child: const Text('加载更多'),
      ),
    );
  }

  // 加载更多新闻
  Future<void> _loadMoreNews() async {
    if (_loadingMoreNews || !_hasMoreNews) return;
    
    setState(() => _loadingMoreNews = true);
    
    try {
      final nextPage = _currentNewsPage + 1;
      final moreNews = await NbaService.fetchNews(page: nextPage);
      
      setState(() {
        if (moreNews.isNotEmpty) {
          _news.addAll(moreNews);
          _currentNewsPage = nextPage;
          _hasMoreNews = moreNews.length >= 20; // 假设每页20条
        } else {
          _hasMoreNews = false;
        }
        _loadingMoreNews = false;
      });
    } catch (e) {
      print('加载更多新闻失败: $e');
      setState(() => _loadingMoreNews = false);
    }
  }

  Widget _buildNewsCard(NbaNews news) {
    final themeConfig = Provider.of<ThemeConfig>(context);
    final primary = themeConfig.currentPrimaryColor;
    return InkWell(
      onTap: () => _openNewsDetail(news),
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (news.imageUrl.isNotEmpty)
              CachedNetworkImage(
                imageUrl: news.imageUrl,
                width: 80,
                height: 80,
                fit: BoxFit.cover,
                placeholder: (context, url) => Container(
                  width: 80,
                  height: 80,
                  color: themeConfig.currentTextColor.withOpacity(0.1),
                  child: Icon(Icons.article, color: themeConfig.currentTextColor.withOpacity(0.4)),
                ),
                errorWidget: (context, url, error) => Container(
                  width: 80,
                  height: 80,
                  color: themeConfig.currentTextColor.withOpacity(0.1),
                  child: Icon(Icons.error, color: themeConfig.currentTextColor.withOpacity(0.4)),
                ),
              ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    news.title,
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 14,
                      color: themeConfig.currentTextColor,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 6),
                  if (news.summary.isNotEmpty)
                    Text(
                      news.summary,
                      style: TextStyle(
                        color: themeConfig.currentTextColor.withOpacity(0.75),
                        fontSize: 14,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  const SizedBox(height: 6),
                  Row(
                    children: [
                      Text(
                        '${news.source} · ${_formatTime(news.publishTime)}',
                        style: TextStyle(color: themeConfig.currentTextColor.withOpacity(0.6), fontSize: 12),
                      ),
                      const Spacer(),
                      Row(
                        children: [
                          Icon(Icons.thumb_up, size: 12, color: themeConfig.currentTextColor.withOpacity(0.5)),
                          const SizedBox(width: 4),
                          Text('${news.likeCount}', style: TextStyle(fontSize: 10, color: themeConfig.currentTextColor.withOpacity(0.6))),
                          const SizedBox(width: 10),
                          Icon(Icons.comment, size: 12, color: themeConfig.currentTextColor.withOpacity(0.5)),
                          const SizedBox(width: 4),
                          Text('${news.commentCount}', style: TextStyle(fontSize: 10, color: themeConfig.currentTextColor.withOpacity(0.6))),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 集锦标签页
  Widget _buildHighlightsTab() {
    if (_highlights.isEmpty && !_loading) {
      return const Center(child: Text('暂无集锦视频'));
    }

    final isWide = MediaQuery.of(context).size.width > 800;

    return RefreshIndicator(
      onRefresh: () async {
        setState(() {
          _currentHighlightsPage = 1;
          _hasMoreHighlights = true;
          _reachedHighlightsBottom = false;
        });
        final highlights = await NbaService.fetchHighlights(page: 1);
        setState(() => _highlights = highlights);
      },
      child: NotificationListener<ScrollNotification>(
        onNotification: (notification) {
          final metrics = notification.metrics;
          if (metrics.maxScrollExtent > 0 &&
              metrics.pixels >= metrics.maxScrollExtent - 32) {
            if (!_reachedHighlightsBottom) {
              setState(() => _reachedHighlightsBottom = true);
            }
          }
          return false;
        },
        child: CustomScrollView(
          slivers: [
            SliverPadding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              sliver: SliverGrid(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: isWide ? 6 : 3,
                  childAspectRatio: 0.66,
                  mainAxisSpacing: 12,
                  crossAxisSpacing: 12,
                ),
                delegate: SliverChildBuilderDelegate(
                  (context, index) {
                    final highlight = _highlights[index];
                    return _buildHighlightCard(highlight);
                  },
                  childCount: _highlights.length,
                ),
              ),
            ),
            if ((_hasMoreHighlights || _loadingMoreHighlights) && _reachedHighlightsBottom)
              SliverToBoxAdapter(child: _buildLoadMoreHighlightsButton()),
          ],
        ),
      ),
    );
  }

  // 加载更多集锦按钮
  Widget _buildLoadMoreHighlightsButton() {
    if (_loadingMoreHighlights) {
      return const Padding(
        padding: EdgeInsets.all(16.0),
        child: Center(child: CircularProgressIndicator()),
      );
    }
    
    if (!_hasMoreHighlights) {
      return const Padding(
        padding: EdgeInsets.all(16.0),
        child: Center(child: Text('没有更多集锦了')),
      );
    }
    
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: ElevatedButton(
        onPressed: _loadMoreHighlights,
        child: const Text('加载更多'),
      ),
    );
  }

  // 加载更多集锦
  Future<void> _loadMoreHighlights() async {
    if (_loadingMoreHighlights || !_hasMoreHighlights) return;
    
    setState(() => _loadingMoreHighlights = true);
    
    try {
      final nextPage = _currentHighlightsPage + 1;
      final moreHighlights = await NbaService.fetchHighMorelights(page: nextPage);
      
      setState(() {
        if (moreHighlights.isNotEmpty) {
          _highlights.addAll(moreHighlights);
          _currentHighlightsPage = nextPage;
          _hasMoreHighlights = moreHighlights.length >= 20; // 假设每页20条
        } else {
          _hasMoreHighlights = false;
        }
        _loadingMoreHighlights = false;
      });
    } catch (e) {
      print('加载更多集锦失败: $e');
      setState(() => _loadingMoreHighlights = false);
    }
  }

  Widget _buildHighlightCard(NbaHighlight highlight) {
    return PosterCard(
      title: highlight.title,
      subtitle: '${highlight.duration} · ${highlight.viewCount}次观看',
      imageUrl: highlight.thumbnail,
      onTap: () => _watchHighlight(highlight.videoUrl),
    );
  }

  // 纪录片标签页
  Widget _buildDocumentariesTab() {
    if (_documentaries.isEmpty) {
      return const Center(child: Text('暂无纪录片'));
    }

    return RefreshIndicator(
      onRefresh: () async {
        final documentaries = await NbaService.fetchDocumentaries();
        setState(() => _documentaries = documentaries);
      },
      child: ListView.builder(
        padding: const EdgeInsets.all(8),
        itemCount: _documentaries.length,
        itemBuilder: (context, index) {
          final doc = _documentaries[index];
          return _buildDocumentaryCard(doc);
        },
      ),
    );
  }

  Widget _buildDocumentaryCard(NbaDocumentary doc) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: InkWell(
        onTap: () => _watchDocumentary(doc.videoUrl),
        child: Padding(
          padding: const EdgeInsets.all(8),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 封面图
              CachedNetworkImage(
                imageUrl: doc.cover,
                width: 100,
                height: 120,
                fit: BoxFit.cover,
                placeholder: (context, url) => Container(
                  width: 100,
                  height: 120,
                  color: Colors.grey[300],
                  child: const Icon(Icons.movie, size: 40, color: Colors.grey),
                ),
                errorWidget: (context, url, error) => Container(
                  width: 100,
                  height: 120,
                  color: Colors.grey[300],
                  child: const Icon(Icons.error, size: 40, color: Colors.grey),
                ),
              ),
              const SizedBox(width: 16),
              
              // 内容信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      doc.title,
                      style: const TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    Row(
                      children: [
                        const Icon(Icons.star, size: 14, color: Colors.amber),
                        const SizedBox(width: 4),
                        Text(
                          doc.rating.toStringAsFixed(1),
                          style: const TextStyle(fontWeight: FontWeight.bold),
                        ),
                        const SizedBox(width: 14),
                        Text(
                          doc.duration,
                          style: const TextStyle(color: Colors.grey),
                        ),
                      ],
                    ),
                    const SizedBox(height: 4),
                    Text(
                      '导演: ${doc.director}',
                      style: const TextStyle(color: Colors.grey),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      doc.description,
                      style: const TextStyle(color: Colors.grey, fontSize: 14),
                      maxLines: 3,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    Wrap(
                      spacing: 8,
                      children: doc.tags.map((tag) => Chip(
                        label: Text(tag, style: const TextStyle(fontSize: 12)),
                        backgroundColor: Colors.blue[50],
                      )).toList(),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 排名标签页
  Widget _buildStandingsTab() {
    if (_teams.isEmpty) {
      return const Center(child: Text('暂无排名数据'));
    }

    return RefreshIndicator(
      onRefresh: () async {
        final teams = await NbaService.fetchTeamStandings();
        setState(() => _teams = teams);
      },
      child: ListView.builder(
        padding: const EdgeInsets.all(8),
        itemCount: _teams.length,
        itemBuilder: (context, index) {
          final team = _teams[index];
          return _buildTeamCard(team, index + 1);
        },
      ),
    );
  }

  Widget _buildTeamCard(NbaTeam team, int rank) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Row(
          children: [
            // 排名
            Container(
              width: 30,
              height: 30,
              decoration: BoxDecoration(
                color: rank <= 3 ? Colors.blue : Colors.grey,
                shape: BoxShape.circle,
              ),
              child: Center(
                child: Text(
                  '$rank',
                  style: const TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
            const SizedBox(width: 16),
            
            // 队徽
            CachedNetworkImage(
              imageUrl: team.logo,
              width: 40,
              height: 40,
              placeholder: (context, url) => const CircleAvatar(
                backgroundColor: Colors.grey,
                child: Icon(Icons.sports_basketball, color: Colors.white),
              ),
              errorWidget: (context, url, error) => const CircleAvatar(
                backgroundColor: Colors.grey,
                child: Icon(Icons.error, color: Colors.white),
              ),
            ),
            const SizedBox(width: 16),
            
            // 球队信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    team.name,
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  Text(
                    '${team.conference} · ${team.division}',
                    style: const TextStyle(color: Colors.grey, fontSize: 12),
                  ),
                ],
              ),
            ),
            
            // 战绩
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text(
                  '${team.wins}胜${team.losses}负',
                  style: const TextStyle(fontWeight: FontWeight.bold),
                ),
                Text(
                  '胜率: ${(team.winPercentage * 100).toStringAsFixed(1)}%',
                  style: const TextStyle(color: Colors.grey, fontSize: 12),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 工具方法
  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);
    
    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }

  // 交互方法
  void _watchLive(NbaLiveSource source, NbaLiveMatch match) async {
    final realUrl = await NbaService.getRealPlayUrl(source.url);
    if (realUrl != null) {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (_) => PlayerPage(
            name: '${match.homeTeam} vs ${match.awayTeam}',
            title: '${match.homeTeam} vs ${match.awayTeam}',
            url: realUrl,
            cover: match.homeLogo,
            sourceSite: source.source,
          ),
        ),
      );
    }
  }

  void _watchHighlight(String url) {
    // 从URL中提取视频ID
    final uri = Uri.parse(url);
    final videoId = uri.queryParameters['vid'];
    
    if (videoId == null) {
      // 如果没有视频ID，直接使用原URL
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (_) => PlayerPage(
            name: 'NBA集锦',
            title: 'NBA集锦',
            url: url,
            cover: null,
            sourceSite: 'NBA官方',
          ),
        ),
      );
      return;
    }
    
    // 显示加载对话框
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const AlertDialog(
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text('正在获取视频播放地址...'),
          ],
        ),
      ),
    );
    
    // 调用API获取真实播放地址
    NbaService.getVideoPlayUrl(videoId).then((playUrl) {
      // 关闭加载对话框
      Navigator.of(context).pop();
      print('获取到的视频播放地址: $playUrl');
      if (playUrl != null && playUrl.isNotEmpty) {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (_) => PlayerPage(
              name: 'NBA集锦',
              title: 'NBA集锦',
              url: playUrl,
              cover: null,
              sourceSite: 'NBA官方',
            ),
          ),
        );
      } else {
        // 如果获取播放地址失败，显示错误信息
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('获取视频播放地址失败')),
        );
      }
    }).catchError((error) {
      // 关闭加载对话框
      Navigator.of(context).pop();
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('获取视频播放地址失败: $error')),
      );
    });
  }

  void _watchDocumentary(String url) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (_) => PlayerPage(
          name: 'NBA纪录片',
          title: 'NBA纪录片',
          url: url,
          cover: null,
          sourceSite: 'NBA官方',
        ),
      ),
    );
  }

  void _openNewsDetail(NbaNews news) {
    // 打开新闻详情页面
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => NbaNewsDetailPage(
          newsId: news.id,
          title: news.title,
          imageUrl: news.imageUrl,
        ),
      ),
    );
  }

  // 赛程标签页
  Widget _buildSchedulesTab() {
    if (_schedules.isEmpty) {
      return const Center(child: Text('暂无赛程数据'));
    }

    return RefreshIndicator(
      onRefresh: () async {
        final schedules = await NbaService.fetchSchedules();
        setState(() {
          _schedules = schedules;
          _hasMoreSchedules = true;
        });
      },
      child: ListView.separated(
        padding: EdgeInsets.zero,
        itemCount: _schedules.length + 1,
        separatorBuilder: (context, index) {
          if (index == 0) return const SizedBox.shrink();
          final themeConfig = Provider.of<ThemeConfig>(context);
          return Divider(
            height: 1,
            thickness: 0.6,
            color: themeConfig.currentTextColor.withOpacity(0.08),
          );
        },
        itemBuilder: (context, index) {
          if (index == 0) {
            return _buildDateNavigation();
          }
          final schedule = _schedules[index - 1];
          return _buildScheduleCard(schedule);
        },
      )
    );
  }

  // 日期导航栏
  Widget _buildDateNavigation() {
    final themeConfig = Provider.of<ThemeConfig>(context);
    final primary = themeConfig.currentPrimaryColor;
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
      color: themeConfig.currentGradient.colors.first,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          ElevatedButton.icon(
            onPressed: _loadPreviousDay,
            icon: const Icon(Icons.arrow_back, size: 16),
            label: const Text('前一天'),
            style: ElevatedButton.styleFrom(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              backgroundColor: primary,
              foregroundColor: Colors.white,
            ),
          ),
          Text(
            _formatCurrentDate(),
            style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
          ),
          ElevatedButton.icon(
            onPressed: _loadNextDay,
            icon: const Icon(Icons.arrow_forward, size: 16),
            label: const Text('后一天'),
            style: ElevatedButton.styleFrom(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              backgroundColor: primary,
              foregroundColor: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  // 格式化当前显示日期
  String _formatCurrentDate() {
    return '${_currentDisplayDate.year}年${_currentDisplayDate.month}月${_currentDisplayDate.day}日';
  }

  // 当前显示的日期
  DateTime _currentDisplayDate = DateTime.now();
  
  // 赛事类型导航栏
  Widget _buildSportTypeNavigation() {
    final themeConfig = Provider.of<ThemeConfig>(context);
    final primary = themeConfig.currentPrimaryColor;
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 8),
      child: TabBar(
        controller: _sportTypeTabController,
        isScrollable: true,
        indicatorSize: TabBarIndicatorSize.label,
        padding: EdgeInsets.zero,
        labelPadding: const EdgeInsets.symmetric(horizontal: 12),
        labelColor: primary,
        unselectedLabelColor: themeConfig.currentTextColor.withOpacity(0.6),
        indicator: UnderlineTabIndicator(
          borderSide: BorderSide(color: primary, width: 2),
        ),
        tabs: SportType.values.map((sportType) {
          return Tab(text: sportType.name);
        }).toList(),
      ),
    );
  }
  
  // 直播日期导航栏
  Widget _buildLiveDateNavigation() {
    final themeConfig = Provider.of<ThemeConfig>(context);
    final primary = themeConfig.currentPrimaryColor;
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
      color: themeConfig.currentGradient.colors.first,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          ElevatedButton.icon(
            onPressed: _loadPreviousLiveDay,
            icon: const Icon(Icons.arrow_back, size: 16),
            label: const Text('前一天'),
            style: ElevatedButton.styleFrom(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              backgroundColor: primary,
              foregroundColor: Colors.white,
            ),
          ),
          Text(
            _formatLiveDate(),
            style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
          ),
          ElevatedButton.icon(
            onPressed: _loadNextLiveDay,
            icon: const Icon(Icons.arrow_forward, size: 16),
            label: const Text('后一天'),
            style: ElevatedButton.styleFrom(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              backgroundColor: primary,
              foregroundColor: Colors.white,
            ),
          ),
        ],
      ),
    );
  }
  
  // 格式化直播日期
  String _formatLiveDate() {
    return '${_currentLiveDate.year}年${_currentLiveDate.month}月${_currentLiveDate.day}日';
  }
  
  // 加载前一天直播比赛
  Future<void> _loadPreviousLiveDay() async {
    if (_loadingLiveMatches) return;
    
    setState(() => _loadingLiveMatches = true);
    
    try {
      final previousDay = _currentLiveDate.subtract(const Duration(days: 1));
      final matches = await NbaService.fetchLiveMatches(
        date: previousDay,
        sportType: _currentSportType,
      );
      
      setState(() {
        _liveMatches = matches;
        _currentLiveDate = previousDay;
        _loadingLiveMatches = false;
      });
    } catch (e) {
      print('加载前一天直播比赛失败: $e');
      setState(() => _loadingLiveMatches = false);
    }
  }
  
  // 加载后一天直播比赛
  Future<void> _loadNextLiveDay() async {
    if (_loadingLiveMatches) return;
    
    setState(() => _loadingLiveMatches = true);
    
    try {
      final nextDay = _currentLiveDate.add(const Duration(days: 1));
      final matches = await NbaService.fetchLiveMatches(
        date: nextDay,
        sportType: _currentSportType,
      );
      
      setState(() {
        _liveMatches = matches;
        _currentLiveDate = nextDay;
        _loadingLiveMatches = false;
      });
    } catch (e) {
      print('加载后一天直播比赛失败: $e');
      setState(() => _loadingLiveMatches = false);
    }
  }

  // 加载前一天赛程
  Future<void> _loadPreviousDay() async {
    if (_loadingMoreSchedules) return;
    
    setState(() => _loadingMoreSchedules = true);
    
    try {
      final previousDay = _currentDisplayDate.subtract(const Duration(days: 1));
      final previousSchedules = await NbaService.fetchSchedules(
        startDate: previousDay,
        endDate: previousDay,
      );
      
      setState(() {
        _schedules = previousSchedules;
        _currentDisplayDate = previousDay;
        _loadingMoreSchedules = false;
      });
    } catch (e) {
      print('加载前一天赛程失败: $e');
      setState(() => _loadingMoreSchedules = false);
    }
  }

  // 加载后一天赛程
  Future<void> _loadNextDay() async {
    if (_loadingMoreSchedules) return;
    
    setState(() => _loadingMoreSchedules = true);
    
    try {
      final nextDay = _currentDisplayDate.add(const Duration(days: 1));
      final nextSchedules = await NbaService.fetchSchedules(
        startDate: nextDay,
        endDate: nextDay,
      );
      
      setState(() {
        _schedules = nextSchedules;
        _currentDisplayDate = nextDay;
        _loadingMoreSchedules = false;
      });
    } catch (e) {
      print('加载后一天赛程失败: $e');
      setState(() => _loadingMoreSchedules = false);
    }
  }

  Widget _buildScheduleCard(NbaSchedule schedule) {
    final themeConfig = Provider.of<ThemeConfig>(context);
    final primary = themeConfig.currentPrimaryColor;
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 比赛状态和时间
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  schedule.status,
                  style: TextStyle(
                    color: _getScheduleStatusColor(schedule.status),
                    fontSize: 12,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Text(
                  schedule.seasonName ?? '',
                  style: TextStyle(color: themeConfig.currentTextColor.withOpacity(0.6), fontSize: 12),
                  textAlign: TextAlign.center,
                ),
                Text(
                  '${schedule.matchTime.toString().substring(0, 16)}',
                  style: TextStyle(color: themeConfig.currentTextColor.withOpacity(0.6), fontSize: 12),                 
                ),
              ],
            ),
            const SizedBox(height: 8),
            
            // 球队信息
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                // 主队
                Expanded(
                  child: Row(
                    children: [
                      CachedNetworkImage(
                        imageUrl: schedule.homeLogo,
                        width: 32,
                        height: 32,
                        placeholder: (context, url) => const CircleAvatar(
                          backgroundColor: Colors.grey,
                          child: Icon(Icons.sports_basketball, size: 16, color: Colors.white),
                        ),
                        errorWidget: (context, url, error) => const CircleAvatar(
                          backgroundColor: Colors.grey,
                          child: Icon(Icons.error, size: 16, color: Colors.white),
                        ),
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          schedule.homeTeam,
                          style: const TextStyle(fontWeight: FontWeight.bold),
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                ),
                // 比分（如果有）
            if (schedule.status == '比赛中')
              // 比赛进行中，显示实时比分、时间和第几节
              Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 实时比分
                  Text(
                    '${schedule.homeScore ?? '0'} - ${schedule.awayScore ?? '0'}',
                    style: TextStyle(
                      color: primary,
                      fontWeight: FontWeight.bold,
                      fontSize: 14,
                    ),
                  ),
                  const SizedBox(height: 4),
                  // 时间和第几节
                  if (schedule.quarter != null || schedule.gameClock != null)
                    Text(
                      '${schedule.quarter ?? ''} ${schedule.gameClock ?? ''}'.trim(),
                      style: TextStyle(
                        color: primary,
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
              ],
              )
            else if (schedule.score != null && schedule.score!.isNotEmpty)
              // 已结束比赛显示最终比分
              Text(
                schedule.score!,
                style: TextStyle(
                  color: themeConfig.currentTextColor.withOpacity(0.7),
                  fontWeight: FontWeight.bold,
                  fontSize: 14,
                ),
              )
            else
              // 未开始比赛显示VS
              Text('VS', style: TextStyle(fontWeight: FontWeight.bold, color: primary.withOpacity(0.8))),
                // 客队
                Expanded(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Expanded(
                        child: Text(
                          schedule.awayTeam,
                          style: const TextStyle(fontWeight: FontWeight.bold),
                          textAlign: TextAlign.right,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      const SizedBox(width: 8),
                      CachedNetworkImage(
                        imageUrl: schedule.awayLogo,
                        width: 32,
                        height: 32,
                        placeholder: (context, url) => const CircleAvatar(
                          backgroundColor: Colors.grey,
                          child: Icon(Icons.sports_basketball, size: 16, color: Colors.white),
                        ),
                        errorWidget: (context, url, error) => const CircleAvatar(
                          backgroundColor: Colors.grey,
                          child: Icon(Icons.error, size: 16, color: Colors.white),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            
            // 场馆和转播信息
            if (schedule.venue.isNotEmpty || schedule.broadcast.isNotEmpty)
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const SizedBox(height: 8),
                  Divider(height: 1, thickness: 0.6, color: themeConfig.currentTextColor.withOpacity(0.08)),
                  const SizedBox(height: 8),
                  if (schedule.venue.isNotEmpty)
                    Text(
                      '场馆: ${schedule.venue}',
                      style: TextStyle(color: themeConfig.currentTextColor.withOpacity(0.6), fontSize: 12),
                    ),
                  if (schedule.broadcast.isNotEmpty)
                    Text(
                      '转播: ${schedule.broadcast}',
                      style: TextStyle(color: themeConfig.currentTextColor.withOpacity(0.6), fontSize: 12),
                    ),
                ],
              ),
          ],
      ),
    );
  }

  Color _getScheduleStatusColor(String status) {
    final themeConfig = Provider.of<ThemeConfig>(context, listen: false);
    final primary = themeConfig.currentPrimaryColor;
    switch (status) {
      case '已结束':
        return themeConfig.currentTextColor.withOpacity(0.6);
      case '比赛中':
        return primary;
      case '未开始':
        return primary.withOpacity(0.8);
      case '延期':
        return primary.withOpacity(0.5);
      default:
        return themeConfig.currentTextColor.withOpacity(0.6);
    }
  }
}
